package com.justnow.offer;

import java.util.HashMap;

/**
 * @author justnow
 * Created on 2020-08-10
 * Description
 */
public class Solution35 {


    /**
     * 方法一：通过map来实现深度拷贝，
     * 时间复杂度：O(n)
     * 空间复杂度：O(n)
     * @param head
     * @return
     */
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        HashMap<Node, Node> map = new HashMap<>();
        Node p = head;
        // 第一遍，只是简单的复制链表中节点
        while (p != null) {
            map.put(p, new Node(p.val));
            p = p.next;
        }
        p = head;
        //第二遍，开始复制节点中的next和random指针
        while (p != null) {
            map.get(p).next = map.get(p.next);
            map.get(p).random = map.get(p.random);
            p = p.next;
        }
        return map.get(head);
    }


}

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
